import React, { Component } from 'react';
import moment from 'moment';
import {
  Form, Input, Tag, Select, Calendar, Badge, Radio, Button, Icon, Table, DatePicker, Popover, Tabs, Checkbox, Popconfirm, message, Modal
} from 'antd';
import Menu from "./Menu";
import LetterElment from "../../../components/LetterElment";
import * as ajax from "../../../services/api";
import '../Task.less';

const FormItem = Form.Item;
const { Search } = Input;
const { Option } = Select;
const { TabPane } = Tabs;
const monthFormat = 'YYYY-MM';
const { MonthPicker } = DatePicker;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const confirm = Modal.confirm;


const options = [
  { label: <LetterElment type="tag" name="A"/>},
  { label: <LetterElment name="B"/>},
  { label: <LetterElment name="C"/>},
  { label: <LetterElment name="D"/>},
];

@Form.create()
export default class TaskDetailBasicInfomation extends Component {
  state = {
    disabled: true,
    currentTab: "2",
    whetherToEdit:true,//点击编辑按钮时的反应
    date: '2018-01',//测试的月份
    dateValue: 0,//某年某月的天数
    dataValueArray: [],
    // comTaskId: '666',//任务的id
    comTaskId: this.props.comTaskId,//任务的id
    shiftAliasAlphaMap: '',//返回班次的英文别名，如 A,B,C
    shiftList: [],//返回班次的信息
    cycleList: [],//返回周期的信息
    allCycleDetailMap:{},//排班周期id所对应的的每天班次名称
    perList: [],//排班人员
    perShiftAllMap: [],//排班人员的本月排班情况
    checkedValues:[],//某一个排班的选中情况
    radioChecked:'',//周期排班选中情况的值
    l_index:0,//暂时下标
    l_key:0,
    monthChange:true,//切换月份是否需要提示
    cancelChange:true,//点击取消时是否需要提示
    xChaLength:'',
    xBianLength:'',
    pagenav: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: total => `总共 ${total} 条`,
      onShowSizeChange: (current, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = current;
        pagenav.pageSize = pageSize;
        this.setState({pagenav});
      },
      onChange: (page, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = page;
        pagenav.pageSize = pageSize;
        this.setState({pagenav});
      },
      total: 0,
    },
    isInPeriod:'',//是否在区间内
    isResetMonth:'',//是否重置月份
    resetMonth:'',//具体重置月份
    startDateValue:'',//任务开始时间
    endDateValue:'',//任务结束时间
  };

  componentDidMount() {
    this.getDateAndMonth();//得到当前的年月
    this.renderTaskGetTaskById();//获得任务的开始结束时间，做不可点击作用
    this.renderInPeriodAndResetMonthData();//当查看模式下切换月份时要获取的数据
    this.taskPerShiftListShift();//获得任务的班次和排班周期
    // this.taskComTaskPer();//获得人员指定月的排班情况
  }

  getDateAndMonth = () => {

    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    month = (month < 10 ? "0" + month : month);
    let mydate = (year.toString() + '-' + month.toString());
    let date_value = this.getDaysInOneMonth(year, month);
    console.log('当前月份的天数', date_value);
    this.renderDateArray(date_value);
    this.setState({
      date: mydate,
      dateValue: date_value
    });
  };

  renderDateArray = (sValue) => {
    const sWed = [];
    for (let i = 1; i <= sValue; i++) {
      i = (i < 10 ? "0" + i.toString() : i.toString());
      sWed.push(i);
    }
    sWed.sort((a, b) => parseInt(a) - parseInt(b));
    this.setState({
      dataValueArray: sWed,
    })
  };

  taskPerShiftListShift = () => {
    ajax.taskComTaskPerShiftListShift({comTaskId: this.state.comTaskId}).then((data) => {
      console.log('获得任务的班次和排班周期', data.data);
      if (data.data) {
        this.setState({
          shiftAliasAlphaMap:data.data.shiftAliasAlphaMap || {},
          shiftList: data.data.shiftList || [],
          cycleList: data.data.cycleList || [],
          allCycleDetailMap:data.data.allCycleDetailMap || {}
        });
      }
    }).catch(err=>{});
  };

  taskComTaskPer = () => {
    console.log('任务月',this.state.date);
    ajax.taskComTaskPerShiftListPerShift({month: this.state.date, comTaskId: this.state.comTaskId}).then((data) => {
      console.log('获得人员指定月的排班情况', data);
      if (data.data.perShiftAllMap.length > 0) {
        this.setState({
          perList: data.data.perList,
          perShiftAllMap: data.data.perShiftAllMap,
          whetherToEdit:true
        });
      }
    }).catch(err=>{})
  };

  renderInPeriodAndResetMonthData = () => {
    ajax.taskComTaskPerShiftPagePerShift({
      comTaskId: this.state.comTaskId,
      key: '',
      month: this.state.date,
      pageSize:'10',
      pageNumber:'1'
    }).then((data) => {
      console.log('查询结果噢噢噢噢',data.data);
      if (data.data) {
        this.setState({
          isInPeriod:data.data.isInPeriod,
          isResetMonth:data.data.isResetMonth,
          resetMonth:data.data.resetMonth,
        });
      }
      if(data.data.resetMonth !== ''){
        let s_val_years = data.data.resetMonth.slice(0,4);
        let s_val_month = data.data.resetMonth.slice(5);
        let date_value = this.getDaysInOneMonth(s_val_years, s_val_month);
        this.renderDateArray(date_value);
        this.setState({
          date: data.data.resetMonth,
          dateValue: date_value
        },()=>{
          this.taskComTaskPer();//获得人员指定月的排班情况
        });
      }
    }).catch(err => {
    });
  };

  renderTaskGetTaskById = () => {
    ajax.taskGetTaskById({
      comTaskId:this.props.comTaskId
    }).then((data)=>{
      if(data.data){
        console.log('开始结束时间',data.data);
        this.setState({
          startDateValue:data.data.startDate,
          endDateValue:data.data.endDate,
        })
      }
    }).catch(err => {
    });
  };

  //获得某年某月的天数
  getDaysInOneMonth = (year, month) => {
    month = parseInt(month, 10);
    let d = new Date(year, month, 0);
    return d.getDate();
  };

  getListData = (value) => {
    let listData;
    switch (value.date()) {
      case 8:
        listData = [
          {type: 'warning', content: 'This is warning event.'},
          {type: 'success', content: 'This is usual event.'},
        ];
        break;
      case 10:
        listData = [
          {type: 'warning', content: 'This is warning event.'},
          {type: 'success', content: 'This is usual event.'},
          {type: 'error', content: 'This is error event.'},
        ];
        break;
      case 15:
        listData = [
          {type: 'warning', content: 'This is warning event'},
          {type: 'success', content: 'This is very long usual event。。....'},
          {type: 'error', content: 'This is error event 1.'},
          {type: 'error', content: 'This is error event 2.'},
          {type: 'error', content: 'This is error event 3.'},
          {type: 'error', content: 'This is error event 4.'},
        ];
        break;
      default:
    }
    return listData || [];
  };

  getMonthData = (value) => {
    if (value.month() === 8) {
      return 1394;
    }
  };

  monthCellRender = (value) => {
    const num = this.getMonthData(value);
    return num ? (
      <div className="notes-month">
        <section>{num}</section>
        <span>Backlog number</span>
      </div>
    ) : null;
  };

  dateCellRender = (value) => {
    const listData = this.getListData(value);
    return (
      <ul className="events">
        {
          listData.map(item => (
            <li key={item.content}>
              <Badge status={item.type} text={item.content}/>
            </li>
          ))
        }
      </ul>
    );
  };

  //时间年月的变化
  dateValueChange = (date, dateString) => {
    // console.log('时间年月的变化', dateString);
    let year = dateString.substring(0, 4);
    let month = dateString.substring(5);
    let s_value = this.getDaysInOneMonth(year, month);
    // console.log('当前月份的天数2', s_value);
    if(this.state.whetherToEdit){
      ajax.taskComTaskPerShiftPagePerShift({
        comTaskId: this.state.comTaskId,
        key: '',
        month: dateString.toString(),
        pageSize:'10',
        pageNumber:'1'
      }).then((data) => {
        console.log('查询结果enenenen',data.data);
        if(data.data.isInPeriod === '1' && data.data.perShiftAllMap.length <= 0){
          message.warning('该月暂无排班数据，请点击【编辑】开始排班');
          return;
        }
        if(data.data.isResetMonth === '1'){
          message.warning('已超过任务期间范围，默认重置为任务的截止月');
          let sd = this.state.resetMonth;
          this.setState({
            date:sd,
          },()=>{
            console.log('asdasdasd',this.state.date);
          });
          return;
        }
        if (data.data) {
          this.setState({
            isInPeriod:data.data.isInPeriod,
            isResetMonth:data.data.isResetMonth,
            resetMonth:data.data.resetMonth,
            perList: data.data.perList,
            perShiftAllMap: data.data.perShiftAllMap || [],
          });
        }
        if(data.data.resetMonth !== ''){
          let s_val_years = data.data.resetMonth.slice(0,4);
          let s_val_month = data.data.resetMonth.slice(5);
          let date_value = this.getDaysInOneMonth(s_val_years, s_val_month);
          this.renderDateArray(date_value);
          this.setState({
            date: data.data.resetMonth,
            dateValue: date_value
          });
        }
      }).catch(err => {
      });
    }else{
      if(this.state.monthChange){
        this.renderDateArray(s_value);
        this.setState({
          date: dateString.toString(),
          dateValue: s_value,
          monthChange:true,
          cancelChange:true,
        });
      }else{
        let _this = this;
        confirm({
          title: '您当前修改的信息未保存，确认切换？',
          okText: '保存并切换',
          cancelText: '直接切换',
          onOk() {
            _this.saveAndSwitch(s_value,dateString);
          },
          onCancel() {
            _this.renderDateArray(s_value);
            _this.setState({
              date: dateString.toString(),
              dateValue: s_value,
              monthChange:true,
              cancelChange:true,
            });
          },
        });
      }
    }
  };

  saveAndSwitch = (s_value,dateString) => {
    ajax.taskComTaskPerShiftSetSinglePerShift({
      comTaskId:this.state.comTaskId,
      month:this.state.date,
    }).then((data)=>{
      this.renderDateArray(s_value);
      this.setState({
        date: dateString.toString(),
        dateValue: s_value,
        monthChange:true,
        cancelChange:true,
      });
    }).catch(err=>{});
  };

  renderShiftList = () => {
    return this.state.shiftList.map((val, key) => {
      return <b key={key} style={{display: 'inline-block', fontWeight: 'normal', padding: '3px 8px'}}><LetterElment
        name={this.state.shiftAliasAlphaMap[val.shiftId]} type="tag"/><span id={val.shiftId}>{val.shiftAlias}</span></b>
    })
  };

  renderCycleList = () => {
    return this.state.cycleList.map((val, key) => {
      return (<div key={key}>
        <p className="item b-color-orange" style={{marginTop:'0px',paddingTop:'0px'}}>{val.cycleAlias}</p>
        <p className="item b-color-green" style={{marginTop:'0px',paddingTop:'0px'}}>{val.cycleShiftName}</p>
      </div>)
    })
  };

  /*
  * 编辑模式
  * */
  //编辑模式下的数据和表头
  renderTableHeadList = () => {
    const columnsData = [];
    this.state.dataValueArray.map((v, k) => {
      columnsData.push({
        title: v,
        dataIndex: (this.state.date.toString() + '-' + v),
        key: (this.state.date.toString() + '-' + v),
        width:205,
        render: (text, record, index) => {
          let isInterval = false;//判断当前时间是否在任务期间内
          let startTime = new Date(Date.parse(this.state.startDateValue.substring(0,10).replace('-','/')));
          let endTime = new Date(Date.parse(this.state.endDateValue.substring(0,10).replace('-','/')));
          let currentTime = new Date(Date.parse((this.state.date.toString() + '-' + v).replace('-','/')));
          if(currentTime >= startTime && currentTime <= endTime){
            isInterval = true;
          }
          const wed = (text !== '' && text !== undefined ? text.split(',') : []);
          const content = (
            <Tabs className="popover-paibang" defaultActiveKey="a1">
              <TabPane tab="排班" key="a1">
                <CheckboxGroup defaultValue={wed} options={this.renderOptions()} onChange={this.onchangeSchedule}/>
                {wed[0] === '0'?  <p id={`lmb-popover-p-${index}-${k}`} className="lmb-popover-p p-clicked" onClick={this.renderRestClick.bind(this, k, index)}>{this.renderRest()}</p> :
                  <p id={`lmb-popover-p-${index}-${k}`} className="lmb-popover-p" onClick={this.renderRestClick.bind(this, k, index)}>{this.renderRest()}</p>}
              </TabPane>
              <TabPane tab="周期排班" key="a2">
                <RadioGroup onChange={this.onChangeRadioData}>
                  {this.renderRadioDataList()}
                </RadioGroup>
              </TabPane>
            </Tabs>
          );
          return (
            isInterval ? <Popconfirm title={content} okText="确定" cancelText="取消" trigger="click"
                                     onConfirm={this.handlePopconfimTask.bind(this, k, index)}
                                     onCancel={this.handleCancelPopconfimTask}
                                     onClick={this.renderRestClickLmb.bind(this, k, index)}
                                     // onMouseEnter={this.renderRestClickLmb.bind(this, k, index)}
            >
              <div className="paneltablecolor-list">
                {wed[0] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[0]]} type="tag"/> : ''}
                {wed[1] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[1]]} type="tag"/> : ''}
                {wed[2] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[2]]} type="tag"/> : ''}
                {wed[3] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[3]]} type="tag"/> : ''}
                {wed[4] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[4]]} type="tag"/> : ''}
                {wed[5] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[5]]} type="tag"/> : ''}
                {wed[6] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[6]]} type="tag"/> : ''}
                {wed[7] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[7]]} type="tag"/> : ''}
              </div>
            </Popconfirm> : <div className="paneltablecolor-list paneltablecolor-list-more" style={{background:'#fafafa'}}>

            </div>
          );
        }
      });
    });
    columnsData.sort((a, b) => parseInt(a.title) - parseInt(b.title));
    columnsData.splice(0, 0, {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 130,
      fixed: 'left',
    });
    columnsData.push({
      title: '操作',
      dataIndex: 'cao',
      key: 'cao',
      render: (text, record, index) => {
        return (<span className="span_hover" style={{fontSize: '12px', color: '#0e6bf2'}} onClick={this.resetShifts.bind(this,record.perId,index)}>重置</span>);
      },
      width: 80,
      fixed: 'right',
    });
    return columnsData;
  };
  renderTableContentList = () => {
    const dataSourceList = this.state.perShiftAllMap.map((v, k) => {
        const value = v;
        value.key = v.perId;
        return value;
    });
    return dataSourceList;
  };


  //弹窗点击确认选择
  handlePopconfimTask = (visible, key, index) => {
    console.log('1',visible);
    console.log('2',key);
    console.log(this.state.perShiftAllMap,'dataValueArray-one');

    const perId = this.state.perShiftAllMap[key]['perId'];
    console.log('perid',perId);

    const s = parseInt(visible) + 1;

    const w_data = (s < 10 ? "0" + s.toString() : s.toString());
    const lmb_data = this.state.date + '-' +w_data;

    let taskShiftType;
    let ids;

    if(this.state.checkedValues.length > 0){
      taskShiftType = 1;
      ids = this.state.checkedValues.toString();
    }

    if(this.state.radioChecked !== ''){
      taskShiftType = 2;
      ids = this.state.radioChecked;
    }

    //要是一进来就点击确定
    if(this.state.checkedValues.length === 0 && this.state.radioChecked === ''){
      let visiblewed = visible + 1;
      let visible1 = (visiblewed < 10 ? "0" + visiblewed.toString() : visiblewed.toString());
      let dayValue = this.state.date + '-'+visible1;
      console.log('qwe',this.state.perShiftAllMap[key][dayValue]);
      ids = this.state.perShiftAllMap[key][dayValue];
      taskShiftType = 1;
    }

    console.log('idsidsids',ids);
    //400314671275442176

    ajax.taskComTaskPerShiftValidateSinglePerShift({
      comTaskId:this.state.comTaskId,
      perId:perId,
      date:lmb_data,
      taskShiftType:taskShiftType,
      ids:ids,
    }).then((data)=>{
      const perShiftAllMap = this.state.perShiftAllMap;
      if(this.state.checkedValues.length > 0){
        perShiftAllMap[key][lmb_data] = this.state.checkedValues.toString();
        this.setState({
          perShiftAllMap,
          monthChange:false,
          cancelChange:false,
        });
      }
      if(this.state.radioChecked !== ''){
        let s_index;
        for(let i in this.state.cycleList){
          if(this.state.cycleList[i].taskSchedulCycleId === this.state.radioChecked){
            s_index = i;
          }
        }
        let s_day = this.state.cycleList[s_index].cycleDays;

        let differ_date = parseInt(this.state.dateValue - s + 1);


        let s_shiftname = this.state.allCycleDetailMap[this.state.radioChecked];
        console.log('天数',s_day);
        console.log('班次2',s_shiftname);
        let k = 1;
        for(let j=0;j<differ_date;j++){
          let sdf = s + j;
          let sdfg_data = (sdf < 10 ? "0" + sdf.toString() : sdf.toString());
          let erty_data = this.state.date + '-' +sdfg_data;
          console.log('jjjj',j);
          perShiftAllMap[key][erty_data] = s_shiftname[k];
          k++;
          if(k === s_day + 1){
            k = 1;
          }
          this.setState({
            perShiftAllMap
          });
        }
      }
      this.setState({
        checkedValues:[],
        radioChecked:'',
        l_index:0,
        l_key:0,
        monthChange:false,
        cancelChange:false,
      });
      this.renderTableContentList();
      this.renderTableContentListExamine();
    },(err)=>{
      console.log('errerr',err);
    });
  };

  //弹窗点击取消选择
  handleCancelPopconfimTask = () => {
    this.setState({
      checkedValues:[]
    });
    this.renderTableContentList();
    this.renderTableContentListExamine();
  };

  //排班的选择
  onchangeSchedule = (checkedValues) => {
    console.log('checked = ', checkedValues);
    if(checkedValues.length >= 1){
      console.log('wedOne');
      if (this.state.checkedValues[0] === '0') {
        console.log('wedTwo');
        message.error('班次与休息不能同时选中');
        checkedValues.splice(0,1);
        const node = document.getElementById(`lmb-popover-p-${this.state.l_index}-${this.state.l_key}`);
        node.classList.remove("p-clicked");
        this.setState({
          checkedValues:checkedValues,
          radioChecked:''
        },()=>{
          console.log('abc',this.state.checkedValues);
        });
      }else{
        checkedValues.sort((a, b) => parseInt(a) - parseInt(b));
        if(checkedValues.includes('0')){
          checkedValues.splice(0,1);
        }
        this.setState({
          checkedValues:checkedValues,
          radioChecked:''
        });
      }
    }else{
      checkedValues.sort((a, b) => parseInt(a) - parseInt(b));
      this.setState({
        checkedValues:checkedValues,
        radioChecked:''
      });
    }
  };

  //编辑模式下的排版周期的单选
  onChangeRadioData = (e) => {
    console.log('radio checked', e.target.value);
    this.setState({
      radioChecked: e.target.value,
      checkedValues:[]
    });
  };

  renderOptions = () => {
    const erty = [];
    this.state.shiftList.map((val, key) => {
      if(val.shiftId !== '0'){
        erty.push({
          label: <b key={key}><LetterElment
            name={this.state.shiftAliasAlphaMap[val.shiftId]} type="tag"/><span
            id={val.shiftId}>{val.shiftAlias}</span></b>,
          value: val.shiftId,
        })
      }
    });
    return erty;
  };

  renderRest = () => {
    return this.state.shiftList.map((val, key) => {
      if(val.shiftId === '0'){
        return <b key={key} style={{display: 'inline-block', fontWeight: 'normal', padding: '3px 8px 3px 40px'}}><LetterElment
          name={this.state.shiftAliasAlphaMap[val.shiftId]} type="tag"/><span id={val.shiftId}>{val.shiftAlias}</span></b>
      }
    });
  };

  renderRestClick = (visible, key, index) => {
    console.log('111',visible);
    console.log('222',key);
    console.log('thisthis',index);
    const node = document.getElementById(`lmb-popover-p-${key}-${visible}`);
    if (node.classList.contains('p-clicked')) {
      node.classList.remove("p-clicked");
      this.setState({
        checkedValues:[]
      })
    } else {
      if(this.state.checkedValues.length > 0){
        message.error('班次与休息不能同时选中');
      }else{
        node.classList.add("p-clicked");
        this.setState({
          checkedValues:['0'],
        })
      }
    }

  };

  renderRestClickLmb = (visible, key, index) => {
    let visiblewed = visible + 1;
    let visible1 = (visiblewed < 10 ? "0" + visiblewed.toString() : visiblewed.toString());
    let dayValue = this.state.date + '-'+visible1;
    console.log('dayday',dayValue);
    console.log(this.state.perShiftAllMap[key][dayValue],'dataValueArray的值');
    let s_value = this.state.perShiftAllMap[key][dayValue].split(",");
    this.setState({
      l_index:key,
      l_key:visible,
      checkedValues:s_value
    });
  };

  resetShifts = (perId,index) => {
    let _this = this;
    confirm({
      title: '您确定取消本次操作？',
      okText: '确定',
      cancelText: '继续排班',
      onOk() {
        _this.resetShiftsData(perId,index);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  resetShiftsData = (perId,index) => {
    console.log('index',index);
    ajax.taskComTaskPerShiftResetSinglePerShift({
      comTaskId:this.state.comTaskId,
      month:this.state.date,
      perId:perId
    }).then((data) => {
      const perShiftAllMap = this.state.perShiftAllMap;
      if(data.data){
        let dataMore = data.data.perShiftAllMap[0];
        perShiftAllMap[index] = dataMore;
        this.setState({
          perShiftAllMap
        })
      }
    }).catch(err=>{})
  };

  renderRadioDataList = () => {
    return this.state.cycleList.map((v, k) => {
      return <Radio key={k} value={v.taskSchedulCycleId}>{v.cycleAlias}</Radio>
    })
  };


  /*
   * 查看模式
   * */
  renderTableHeadListExamine = () => {
    const columnsData = [];
    this.state.dataValueArray.map((v, k) => {
      columnsData.push({
        title: v,
        dataIndex: (this.state.date.toString() + '-' + v),
        key: (this.state.date.toString() + '-' + v),
        width:205,
        render: (text, record, index) => {

          let isInterval = false;//判断当前时间是否在任务期间内
          let startTime = new Date(Date.parse(this.state.startDateValue.substring(0,10).replace('-','/')));
          let endTime = new Date(Date.parse(this.state.endDateValue.substring(0,10).replace('-','/')));
          let currentTime = new Date(Date.parse((this.state.date.toString() + '-' + v).replace('-','/')));
          if(currentTime >= startTime && currentTime <= endTime){
            isInterval = true;
          }

          const wed = (text !== '' && text !== undefined ? text.split(',') : []);
          return (
          isInterval ? <div className="paneltablecolor-list wed">
              {wed[0] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[0]]} type="tag"/> : ''}
              {wed[1] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[1]]} type="tag"/> : ''}
              {wed[2] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[2]]} type="tag"/> : ''}
              {wed[3] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[3]]} type="tag"/> : ''}
              {wed[4] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[4]]} type="tag"/> : ''}
              {wed[5] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[5]]} type="tag"/> : ''}
              {wed[6] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[6]]} type="tag"/> : ''}
              {wed[7] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[7]]} type="tag"/> : ''}
              {wed[8] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[8]]} type="tag"/> : ''}
              {wed[9] !== undefined ? <LetterElment name={this.state.shiftAliasAlphaMap[wed[9]]} type="tag"/> : ''}
          </div> : <div className="paneltablecolor-list paneltablecolor-list-more" style={{background:'#fafafa'}}> </div>
          );
        }
      });
    });
    columnsData.sort((a, b) => parseInt(a.title) - parseInt(b.title));
    columnsData.splice(0, 0, {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 130,
      fixed: 'left',
    });
    return columnsData;
  };

  renderTableContentListExamine = () => {
    const dataSourceList = this.state.perShiftAllMap.map((v, k) => {
      const value = v;
      value.key = v.perId;
      return value;
    });
    return dataSourceList;
  };


  contains = (arr, obj) => {
    let i = arr.length;
    while (i--) {
      if (arr[i] === obj) {
        return true;
      }
    }
    return false;
  };

  indexOfData = (arr, str) => {
    // 如果可以的话，调用原生方法
    if(arr && arr.indexOf){
      return arr.indexOf(str);
    }

    let len = arr.length;
    for(let i = 0; i < len; i++){
      // 定位该元素位置
      if(arr[i] === str){
        return i;
      }
    }

    // 数组中不存在该元素
    return -1;
  };

  // /* 编辑模式 */
  // renderListPanel = () => {
  //   return (<div className="tabPanel lmb-tabpanel">
  //     <Table pagination={false} bordered dataSource={this.renderTableContentList()} columns={this.renderTableHeadList()} scroll={{ x: parseInt(this.state.dateValue * 205 + 210),y:560 }} />
  //   </div>);
  // };
  //
  // /* 查看模式 */
  // renderExaminePanel = () => {
  //   return (<div className="tabPanel lmb-tabpanel">
  //     <Table pagination={this.state.pagenav} bordered dataSource={this.renderTableContentListExamine()} columns={this.renderTableHeadListExamine()} scroll={{ x: parseInt(this.state.dateValue * 205 + 130) }} />
  //   </div>);
  // };


  /* 日历模式 */
  renderDatePanel = () => {
    return (<div className="tabPanel">
      <Calendar className="TaskDetailPersonnelPlacement-Calendar" dateCellRender={this.dateCellRender} monthCellRender={this.monthCellRender} />
      <div className="bj-list">
        <div className="bj-item b-orange">
          <div className="bj-top">
            <div className="item"><span className="color-orange">A</span>班次A: <em>9:00〜10:00</em></div>
            <Button size="small" type="primary" ghost>添加人员</Button>
          </div>
          <div className="bj-user-list">
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
          </div>
        </div>
        <div className="bj-item g-orange">
          <div className="bj-top">
            <div className="item"><span className="color-green">A</span>班次A: <em>9:00〜10:00</em></div>
            <Button size="small" type="primary" ghost>添加人员</Button>
          </div>
          <div className="bj-user-list">
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
          </div>
        </div>
        <div className="bj-item c-orange">
          <div className="bj-top">
            <div className="item"><span className="color-cyan">A</span>班次A: <em>9:00〜10:00</em></div>
            <Button size="small" type="primary" ghost>添加人员</Button>
          </div>
          <div className="bj-user-list">
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
            <div className="bj-user"><Icon type="user" />陈小二</div>
          </div>
        </div>
      </div>

    </div>);
  };

  //保存
  saveData = () => {
    ajax.taskComTaskPerShiftSetSinglePerShift({
      comTaskId:this.state.comTaskId,
      month:this.state.date,
    }).then((data)=>{
      console.log('成功！');
      this.setState({
        monthChange:true,
        cancelChange:true,
        whetherToEdit:true
      });
      this.renderDatePanel();
    }).catch(err=>{});
  };

  //取消
  cancelData = () => {
    if(!this.state.cancelChange){
      this.taskComTaskPer();
    }else{
      let _this = this;
      confirm({
        title: '您确定取消本次操作？',
        okText: '确定',
        cancelText: '继续排班',
        onOk() {
          _this.taskComTaskPer();
        },
        onCancel() {

        },
      });
    }
  };

  //点击搜索
  searchContent = (sVal) => {
    ajax.taskComTaskPerShiftPagePerShift({
      comTaskId: this.state.comTaskId,
      key: sVal,
      month: this.state.date,
      pageSize:'10',
      pageNumber:'1'
    }).then((data) => {
      console.log('查询结果',data.data);
      if (data.data) {
        this.setState({
          perShiftAllMap: data.data.perShiftAllMap
        });
      }
    }).catch(err => {
    });
  };


  render() {

    const { getFieldDecorator } = this.props.form;
    //判断是否显示编辑状态或者是查看状态
    let isExamineShow = '';
    let isEditShow = '';
    if(this.state.whetherToEdit){
      isExamineShow = 'block';
      isEditShow = 'none';
    }else{
      isExamineShow = 'none';
      isEditShow = 'block';
    }

    return (
      <div className="TaskDetail TaskDetailPersonnelPlacement">
        {/*<div className="taskdetail-title">*/}
          {/*任务名称 <Tag>进行中</Tag>*/}
        {/*</div>*/}
        {/*<Menu current={4} />*/}
        <div className="info">
          <div className="list">
            <span className="label">班次：</span>
            {this.renderShiftList()}
          </div>
          <div className="list zlist">
            <span className="label">排班周期：</span>
            {this.renderCycleList()}
          </div>
        </div>


        <div className="form">
          <Form
            onSubmit={this.handleSubmit}
            layout="inline"
            style={{display:'flex',justifyContent:'space-between'}}
          >
            <div>
              {this.state.whetherToEdit ? <Button type="primary" ghost style={{marginTop:'4px'}} onClick={()=>{
                this.setState({
                  whetherToEdit:false
                });
              }}>编辑</Button> : ''}
            </div>
            <div>
              <MonthPicker style={{marginTop:'4px'}} value={moment(this.state.date, monthFormat)} format={monthFormat} onChange={this.dateValueChange}/>

              {this.state.whetherToEdit ?  <FormItem style={{marginRight:'0px',marginLeft:'10px',marginTop:'0px'}}>
                {getFieldDecorator('address', {
                  rules: [{message: '请输入搜索内容'}],
                })(
                  <Search
                    placeholder="请输入搜索内容"
                    onSearch={value => this.searchContent(value)}
                    style={{width: 200}}
                    enterButton
                  />
                )}
              </FormItem> : ''}
              {/*<Radio.Group value={this.state.currentTab} className="ant-radio-group-self" >*/}
              {/*<Radio.Button onClick={() => { this.setState({ currentTab: "1" }); }} value="1">日历模式</Radio.Button>*/}
              {/*<Radio.Button onClick={() => { this.setState({ currentTab: "2" }); }} value="2">列表模式</Radio.Button>*/}
              {/*</Radio.Group>*/}
            </div>
          </Form>
          {/*{this.state.currentTab === "1" ? this.renderDatePanel() : this.renderListPanel()}*/}

          {/*{this.state.whetherToEdit ? this.renderExaminePanel() : this.renderListPanel()}*/}

          <div>
            <div className="oneContent" style={{display: isExamineShow}}>
              <div className="tabPanel lmb-tabpanel">
                <Table pagination={this.state.pagenav} bordered dataSource={this.renderTableContentListExamine()} columns={this.renderTableHeadListExamine()} scroll={{ x: parseInt(this.state.dateValue * 205 + 130) }} />
              </div>
            </div>
            <div className="twoContent" style={{display:isEditShow}}>
              <div className="tabPanel lmb-tabpanel">
                <Table pagination={false} bordered dataSource={this.renderTableContentList()} columns={this.renderTableHeadList()} scroll={{ x: parseInt(this.state.dateValue * 205 + 210),y:560 }} />
              </div>
            </div>
          </div>

          {this.state.whetherToEdit ? '' :  <div className="btn-box">
            <Button onClick={this.cancelData}>取消</Button>
            <Button type="primary" onClick={this.saveData}>保存</Button>
          </div>}
        </div>
      </div>
    );
  }
}

